<template>
  <div class="box">
    <div
      class="boxLabel"
      :class="{
        changeBoxLabelBg: !showNodes && root.children.length !== 0,
        nodeDraggable: !root.if,
        enterBg: root.hover,
      }"
      @click="hideOrShowNode"
      :draggable="root.if"
      @dragstart="dragstart($event, root, nodeArr)"
      @drop="drop($event, root, nodeArr)"
      @dragend="dragend($event, root, nodeArr)"
      @dragover="dragover($event, root)"
      @dragleave="dragleave($event, root)"
      @dragenter="dragenter($event, root)"
    >
      <!-- <div class="boxLabelCard"> -->
        <!-- <div class="mainPartChoose" v-if="root.type === '公司'">
          <div class="companyOrDepartment">
            <span class="title">{{ root.type === "公司" ? "公司" : "部门" }}：</span>
            <span class="titleName">{{ root.name }}</span>
          </div>
          <div class="boxLabelCardInfo">
            <div class="message district" v-if="root.district">
              <span>地区：</span>
              <span>{{ root.district }}</span>
            </div>
            <div class="message belongTo" v-if="root.type === '部门'">
              <span>归属：</span>
              <span>{{ root.ascription }}</span>
            </div>
            <div class="message">
              <span>负责人：</span>
              <span>{{ root.leader ? root.leader : "无" }}</span>
            </div>
            <div class="message">
              <span>人数：</span>
              <span>{{ root.members }}</span>
            </div>
            <div class="message estableDate" v-if="root.type === '公司'">
              <span>成立日期：</span>
              <span>{{ getDate(root.estableDate) }}</span>
            </div>
            <div class="message"></div>
          </div>
        </div> -->
        <company-card v-if="root.type === '公司' || root.type === '部门'" :companyAndDep="root"></company-card>
        <!-- <department-card v-else :departmentData="root"></department-card> -->
        <employee-card v-else :employeeData="root"></employee-card>
      <!-- </div> -->
    </div>
    <div
      class="box-children"
      v-if="root.children.length !== 0"
      v-show="showNodes"
    >
      <box
        v-for="node in root.children"
        :key="node.index"
        :root="node"
        :nodeArr="root.children"
      ></box>
    </div>
  </div>
</template>

<script>
import CompanyCard from '@/components/CompanyCard'
import DepartmentCard from '@/components/DepartmentCard'
import EmployeeCard from '@/components/EmployeeCard'

export default {
  name: "Box",
  components:{EmployeeCard, CompanyCard, DepartmentCard},
  data() {
    return {
      showNodes: false,
      dragNodeIndex: -1, //drag节点在父元素中的索引，初始设置为-1
      isHoverNow: false,
    };
  },
  props: {
    root: {
      type: Object,
    },
    nodeArr: {
      type: Array || null,
    },
    
  },
  methods: {
    hideOrShowNode() {
      this.showNodes = !this.showNodes;
    },
   
    eleToLast(arr, e) {
      //数组某个元素放到最后一位
      let newArr = [];
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].name !== e.name) {
          newArr.push(arr[i]);
        }
      }
      newArr.push(e);
      return newArr;
    },
    checkDropNodeIsDragsSon(dragNode, dropNode) {
      //判断放置点元素是否为拖曳节点子元素
      if (dragNode.children.length === 0) return false;
      let newArr = [];
      function getAllName(dragNode) {
        newArr.push(dragNode.name);
        if (dragNode.children.length === 0) {
          return;
        } else {
          for (let i = 0; i < dragNode.children.length; i++) {
            getAllName(dragNode.children[i]);
          }
        }
      }
      getAllName(dragNode);
      if (newArr.includes(dropNode.name)) {
        return true;
      }
      return false;
    },
    //drag事件
    dragstart(e, root, nodeArr) {
      this.$store.state.dragID = root.id; //记录拖动的节点ID
      this.$store.state.dropNodeName = ""; //初始化放置点
      this.$store.state.drapNodeName = root.name; //全局状态保存drag节点的名称
      this.dragNodeIndex = nodeArr.findIndex(
        (item) => JSON.stringify(item) === JSON.stringify(root)
      ); //找到drag节点在原父节点的index

      let transNodeData = JSON.stringify(root); //传递节点数据，装换为JSON
      e.dataTransfer.setData("node", transNodeData);
    },
    dragenter(e, root) {
      e.preventDefault();
    },
    dragover(e, root) {
      e.preventDefault();
      if (this.$store.state.drapNodeName === root.name) return;
      root.hover = true;
    },
    dragleave(e, root) {
      if (this.$store.state.drapNodeName === root.name) return;
      root.hover = false;
    },
    drop(e, root, nodeArr) {
      root.hover = false;
      console.log(`放置到节点🚀${root.name}`, root);
      this.$store.state.dropID = root.id;
      let nodeNameArr = []; //用来接收放置点位的子元素name
      this.$store.state.dropNodeName = root.name; //保存放置点名称
      //获取节点数据
      let graftingData = e.dataTransfer.getData("node");
      let parsedData = JSON.parse(graftingData);

      //用来判断是否拖曳父节点移动到子节点了，如果为true就取消操作
      this.$store.state.fatherToSon = this.checkDropNodeIsDragsSon(
        parsedData,
        root
      );
      if (this.$store.state.fatherToSon) return;
      //fatherToSon为ture就取消操作
      else if (this.$store.state.drapNodeName === root.name) {
        //如果是自移位，就啥也不做
        console.log("drop1️⃣drag和drop是同一位置，不操作!!!!!!!🌈🌈");
        return;
      } else if (root.children.length === 0) {
        //如果放置点没有子节点
        //root.children可能初始值为null或者变为0
        console.log("drop2️⃣放置位置没有子节点，添加子节点");
        root.children = [parsedData];
      } else {
        root.children.map((item) => nodeNameArr.push(item.name));
        // console.log('🐉获取父节点的子节点数组信息',nodeNameArr)
        if (nodeNameArr.includes(this.$store.state.drapNodeName)) {
          //判断是否移动到父节点了
          this.$store.state.moveToFaterNode = true;
          console.log(
            "drop3️⃣移动到👨节点了,把drag元素放到最后面，并设置一个trigger",
            this.$store.state.moveToFaterNode
          );
          root.children = this.eleToLast(root.children, parsedData);
        } else {
          //如果是非空数组就直接添加
          console.log("drop4️⃣");
          root.children.push(parsedData);
        }
      }
    },
    dragend(e, root, nodeArr) {
      let trigger = e.dataTransfer.dropEffect; //获取鼠标状态
      e.dataTransfer.effectAllowed = "copy";
      console.log(e.dataTransfer.effectAllowed);
      console.log(trigger, "🐯");
      //先判断是否为chrome浏览器
      if (
        navigator.userAgent.indexOf("Chrome") &&
        navigator.userAgent.indexOf("Win64") > 0
      ) {
        if (trigger === "copy") {
          //已判定为放置状态
          if (this.$store.state.dropNodeName == root.name) {
            //如果是自移位，就啥也不做
            console.log("dragend1️⃣自移位，dragend啥也不做");
            return;
          } else if (this.$store.state.moveToFaterNode) {
            //判断是不是在父节点添加
            this.$store.state.moveToFaterNode = false; //状态复位
            console.log("dragend3️⃣操作，在父节点了，dragend不作操作了");
            return;
          } else {
            console.log("dragend4️⃣删除节点");
            if (this.$store.state.fatherToSon) {
              console.log("👿父到子了，不允许");
              return;
            } //
            nodeArr.splice(this.dragNodeIndex, 1);
            let id = this.$store.state.dragID;
            let cid = this.$store.state.dropID;
            console.log("🚀🌠", id, cid);
            // 和数据库同步
            this.ajax(id, cid);
          }
        } else if (trigger === "move") {
          // if(navigator.userAgent.indexOf("Chrome")>0){return}
          console.log("dragend5️⃣鼠标状态为copy，啥也不做1");
          return;
        } else if (trigger === "none") {
          //判定为未放置状态
          console.log("dragend6️⃣鼠标状态为none，啥也不做");
          return;
        }
      } else {
        //其他浏览器执行
        if (trigger === "move") {
          //已判定为放置状态
          if (this.$store.state.dropNodeName == root.name) {
            //如果是自移位，就啥也不做
            console.log("dragend1️⃣自移位，dragend啥也不做");
            return;
          } else if (this.$store.state.moveToFaterNode) {
            //判断是不是在父节点添加
            this.$store.state.moveToFaterNode = false; //状态复位
            console.log("dragend3️⃣操作，在父节点了，dragend不作操作了");
            return;
          } else {
            console.log("dragend4️⃣删除节点");
            if (this.$store.state.fatherToSon) {
              console.log("👿父到子了，不允许");
              return;
            } //
            nodeArr.splice(this.dragNodeIndex, 1);
            let id = this.$store.state.dragID;
            let cid = this.$store.state.dropID;
            console.log("🚀🌠", id, cid);
            // 和数据库同步
            this.ajax(id, cid);
          }
        } else if (trigger === "copy") {
          // if(navigator.userAgent.indexOf("Chrome")>0){return}
          console.log("dragend5️⃣鼠标状态为copy，啥也不做");
          return;
        } else if (trigger === "none") {
          //判定为未放置状态
          console.log("dragend6️⃣鼠标状态为none，啥也不做");
          return;
        }
      }
    },
    ajax(id, cid) {
      console.log("数据跟新...");
      var request = new XMLHttpRequest();
      request.onreadystatechange = (res) => {
        if (request.readyState === 4) {
          if (request.status >= 200 && request.status < 300) {
            // console.log(request.response);
          } else if (request.status >= 400) {
            console.log("请求失败");
          }
        }
      };
      request.open(
        "GET",
        `http://106.52.79.181:9882/myehr/ComDep/comDepUp.action?id=${id}&pid=${cid}&swaggerUserCode=sysadmin`
      );
      request.send();
      // return request.response
    },
  },
};
</script>

<style lang="scss">
/* :root{--color:purple} */
.box {
  display: flex;
  width: auto;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
  position: relative;
  font-size: 18px;
  color: #fff;
  &::before,
  &::after {
    content: "";
    position: absolute;
    height: 24px;
    width: 50%;
    left: 0;
    top: 0;
    border-right: 1px solid #dddddd;
  }

  &:not(:first-child)::before {
  border-top: 1px solid #dddddd;
  }
  &:not(:last-child)::after {
    left: 50%;
    border-right: none;
    border-top: 1px solid #dddddd;
  }

  .boxLabel {
    height: 100px;
    width: 240px;
    font-size: 16px;
    background-color: lightpink;
    background-image: url(~@/assets/linearBlue.jpg);
    background-size: cover;
    margin: 24px 24px 0 24px;
    line-height: 40px;
    cursor: pointer;
    user-select: none;
    display: flex;
    justify-content: center;
    align-items: center;
    // padding: 12px;
    border-radius: 8px;
    //公司的的背景和鼠标样式
    &.nodeDraggable {
      background-image: url(~@/assets/linearGreen.jpg) ;
      cursor: no-drop
    }
    //drageover时候的样式
    &.enterBg {
      background-image: url(~@/assets/linearPink.jpg);
    }

    .boxLabelCard {
      display: inline;
      flex-direction: column;
      height: auto;
      width: 100%;
      line-height: 1.5;
      div>span:first-child{
        padding: 0 .5em 0 1em;
      } 
      
      .companyOrDepartment {
        display: flex;
        justify-content: flex-start;
        line-height: 1.5;
        height: 1.5;
        margin-bottom: 5px;
        text-overflow: ellipsis;
        white-space: nowrap;
        // font-size: 18px;
        .title {
          font-weight: 700;
        }
        .titleName{
          overflow: hidden;
          display: inline-block;
          text-overflow: ellipsis;
          white-space: nowrap;

        }
      }

      .boxLabelCardInfo {
        font-size: 16px;
        width: 100%;
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
        height: 100%;
          .message{
            display: flex;
            width:50%;
            white-space: nowrap;
            text-align: left;
            &.estableDate, &.belongTo, &.district{
              width: 100%;
            }
          }
      }
    }
  }

  .changeBoxLabelBg {
    background-color: lightgreen;
  }
  .box-children {
    display: inline-flex;
    width: auto;
    position: relative;
    padding-top: 24px;
  }
  .box-children::before {
    content: "";
    position: absolute;
    height: 24px;
    top: 0;
    left: 50%;
    border-left: 1px solid #dddddd;
  }
}
//去除顶部公司的天线
#app > .box::after,
#app > .box::before {
  content: none;
}

</style>
